package com.cm.log_process.log_settings.service.impl;

import com.cm.log_process.log_settings.service.SettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.client.TransportClientFactoryBean;
import org.springframework.stereotype.Service;

/**
 * Creator:郭兆鹏
 * Date:2019/12/26
 * 思路：修改ES集群配置外部接口
 */
@Slf4j
@Service
public class SettingServiceImpl implements SettingService {

    @Autowired
    private TransportClientFactoryBean factoryBean;

    //设置最大索引数
    @Override
    public boolean setMaxResult(String indexName,String maxRes) throws Exception {
        log.info("**************************准备更新设置，最大返回结果:"+maxRes+"**************************");
        TransportClient client = factoryBean.getObject();
        UpdateSettingsResponse response = client.admin().
                indices().           //多索引操作
                prepareUpdateSettings(indexName).        //索引名
                setSettings(Settings.builder().put("index.max_result_window", maxRes).build()).get();
        log.info("**************************更新完成，等待响应结果**************************");
        return response.isAcknowledged();
    }

    @Value("${elasticsearch.type}")
    private String type;

    @Override
    public boolean setFieldData(String indexName, String fieldName) throws Exception {
        log.info("**************************设置fieldData字段，可排序字段设置**************************");
        TransportClient client = factoryBean.getObject();
        PutMappingResponse putMappingResponse = client.admin().indices().
                preparePutMapping(indexName)
                .setType(type)
                .setSource("{\n" +
                        "  \"log\": {\n" +
                        "    \"properties\": {\n" +
                        "      \"timestamp\": {\n" +
                        "        \"type\": \"text\",\n" +
                        "        \"fielddata\": true\n" +
                        "      }\n" +
                        "    }\n" +
                        "  }\n" +
                        "}", XContentType.JSON).get();
        //返回响应结果
        log.info("**************************更新完成，等待响应结果**************************");
        return putMappingResponse.isAcknowledged();
    }

    @Override
    public boolean createIndex(String indexName) throws Exception {
        log.info("**************************创建索引**************************");
        if(!indexExists(indexName)){
            TransportClient client = factoryBean.getObject();
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
            try {
                ActionFuture<CreateIndexResponse> future = client.admin().indices().create(createIndexRequest);
                log.info("**************************索引创建完毕**************************");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.warn("**************************索引创建异常**************************");
        return false;

    }

    private boolean indexExists(String indexName) throws Exception {
        log.info("开始检测是否存在该索引...");
        TransportClient client = factoryBean.getObject();
        IndicesAdminClient indices = client.admin().indices();
        IndicesExistsRequest request = new IndicesExistsRequest(indexName);
        IndicesExistsResponse response = indices.exists(request).actionGet();
        log.info("索引检索完毕...");
        if(response.isExists()) {
            log.info("已存在该索引...");
            return true;
        }
        log.info("不存在该索引...");
        return false;
    }
}
